package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
@Slf4j
public class SessionController {
    //会话跟踪-cookie
    //设置cookie
    @GetMapping("/c1")
    public Result cookie1(HttpServletResponse httpServletResponse){
        httpServletResponse.addCookie(new Cookie("login_username","itheima"));
        return Result.success();
    }
    //获取cookie
    @GetMapping("/c2")
    public Result cookie2(HttpServletRequest httpServletRequest){
        Cookie[] cookies = httpServletRequest.getCookies();
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("login_username")){
                System.out.println("login_username:"+cookie.getValue());
            }
        }
        return Result.success();
    }

    //会话跟踪session
    //往HttpSession中存储值
    @GetMapping("s1")
        public Result session1(HttpSession httpSession) {
            log.info("HttpSession1:{}",httpSession.hashCode());
            httpSession.setAttribute("loginUser","itheima");
            return Result.success();
    }

    //从HttpSession中获取值
    @GetMapping("/s2")
    public Result session2(HttpSession session){
        log.info("HttpSession2:{}",session.hashCode());
        Object loginUser = session.getAttribute("loginUser");
        log.info("loginUser:{}",loginUser);
        return Result.success();
    }

    //从HttpServletRequest中获取HttpSession
    @GetMapping("/s3")
    public Result session3(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        log.info("HttpSession3:{}",session.hashCode());
        Object loginUser = session.getAttribute("loginUser");
        log.info("loginUser:{}",loginUser);
        return Result.success();
    }
}
